// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({    env: "dzc-aapp-0g1mx02g41e97626", }) // 使用当前
const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
    let {
        type,
        imgUrl
    } = event;
    if (type ==='shenfenzheng') {
        try {
            const result = await cloud.openapi.ocr.idcard({
                type: 'photo',
                imgUrl: imgUrl
            });
            console.log('OCR 识别结果:', result); 
            if (result && result.name && result.id && result.addr && result.gender && result.nationality && result.birth) {
                const idNumber = result.id;
                const name = result.name;
                const addr = result.addr;
                const gender = result.gender;
                const nationality = result.nationality;
                const birth = result.birth;

                const wxContext = cloud.getWXContext()
                const openid = wxContext.OPENID

                await db.collection('identity_verification').add({
                    data: {
                        _openid: openid,
                        idNumber,
                        name,
                        addr,
                        gender,
                        nationality,
                        birth,
                        createTime: db.serverDate()
                    }
                })

                return {
                    idNumber,
                    name,
                    addr,
                    gender,
                    nationality,
                    birth,
                    status: 'ok'
                };
            } else {
                console.error('识别结果缺少必要信息:', result);
                return {
                    status: 'error',
                    message: '识别结果缺少必要信息'
                };
            }
        } catch (err) {
            console.log(err);
            return {
                status: 'error',
                message: err.message
            };
        }
    }
    return {
        status: 'error',
        message: '不支持的识别类型'
    };
};